#include <iostream>
#include <string>
#include <mysql/mysql.h>

using namespace std;

string host = "127.0.0.1"; // 'localhost'
string user = "root";
string passwd = "Zh_shuoshuo20030206.";
string db = "test_db";
unsigned int port = 3306;

void add(MYSQL* mysql)
{
    const char* sql = "insert into test_tb (id, name, age, score) values (11, '小张', 18, 77.5);";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        cerr << "query sql failed: " << mysql_errno(mysql) << endl;
        return;
    }
}

void mod(MYSQL* mysql)
{
    const char* sql = "update test_tb set name='小王' where id=11;";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        cerr << "query sql failed: " << mysql_errno(mysql) << endl;
        return;
    }
}

void del(MYSQL* mysql)
{
    const char* sql = "delete from test_tb where id=11;";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        cerr << "query sql failed: " << mysql_errno(mysql) << endl;
        return;
    }
}

void get(MYSQL* mysql)
{
    const char* sql = "select * from test_tb;";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        cerr << "query sql failed: " << mysql_errno(mysql) << endl;
        return;
    }
    
    // 保存结果集到本地
    MYSQL_RES* res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        cerr << "store result failed: " << mysql_errno(mysql) << endl;
        return;
    }
    
    // 获取结果集的行数和列数
    int row_num = mysql_num_rows(res);
    int col_num = mysql_num_fields(res);

    // 遍历结果集，获取每一行数据
    for (int i = 0; i < row_num; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < col_num; j++)
        {
            cout << row[j] << "\t|\t"; 
        }
        cout << endl;
    }

    // 释放结果集
    mysql_free_result(res);
}

int main()
{
    // 初始化操作句柄
    MYSQL* mysql = mysql_init(nullptr);
    if (mysql == nullptr)
    {
        cerr << "mysql_init error" << endl;
        return -1;
    }

    // 连接mysql服务器
    if (mysql_real_connect(mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        cerr << "connect mysql server failed!" << endl;
        return -1;
    }

    // 设置当前客户端的字符集
    mysql_set_character_set(mysql, "utf8");
    cout << "mysql_real_connect success!!" << endl;

    // add(mysql);
    // mod(mysql);
    // del(mysql);
    get(mysql);

    // 关闭MySQL对象
    mysql_close(mysql);

    return 0;
}
